// 单例模式
const loadScript = (function () {
  const caches = [] // 缓存列表

  return (url) => {
    if (caches.includes(url)) return Promise.resolve()

    return new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.type = 'text/javascript'

      if (script.readyState) {
        script.onreadystatechange = function () {
          if (script.readyState == 'loaded' || script.readyState == 'complete') {
            script.onreadystatechange = null
            caches.push(url)
            resolve()
          }
        }
      } else {
        script.onload = function () {
          caches.push(url)
          resolve()
        }
        script.onerror = function () {
          console.log(`load js fail:${url}`)
          reject()
        }
      }

      script.src = url
      document.body.appendChild(script)
    })
  }
})()
export default {
  loadTianMap(tdtAk) {
    //const tdtAk = store.state.commonConfig.tdtAk
    if (!tdtAk) return Promise.resolve()
    return loadScript(`${window.location.protocol}//api.tianditu.gov.cn/api?v=4.0&tk=${tdtAk}`)
  },
  loadBaiduMap(baiduAk) {
    //const baiduAk = store.state.commonConfig.baiduAk
    if (!baiduAk) return Promise.resolve()
    if (window.location.protocol.startsWith('https')) window.HOST_TYPE = '2' // https 下百度地图特殊记号
    window.BMap_loadScriptTime = new Date().getTime()
    return loadScript(`${window.location.protocol}//api.map.baidu.com/getscript?v=2.0&ak=${baiduAk}&services=&t=${new Date().getTime()}`)
    // return loadScript(`${window.location.protocol}//api.map.baidu.com/api?type=webgl&v=1.0&ak=${baiduAk}`)
  }
}
